package org.springframework.web.servlet.view;

import org.springframework.beans.BeanUtils;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.excel.AppExcelView;
import org.springframework.web.servlet.view.pdf.AppPdfView;

import java.util.Locale;

/**
 * Created by 1 on 2016/4/18.
 */
public class ReportViewResolver extends AbstractCachingViewResolver implements Ordered {

    private static final String EXCEL_URL_PREFIX = "excel:";
    private static final String PDF_URL_PREFIX = "pdf:";

    private String prefix = "";
    private int order = Integer.MAX_VALUE;

    @Override
    protected View loadView(String viewName, Locale locale) throws Exception {
        // Check for special "excel:" prefix.
        if (viewName.startsWith(EXCEL_URL_PREFIX) && !viewName.endsWith(".xls")) {
            return getExcelView(viewName);
        }
        // Check for special "pdf:" prefix.
        if (viewName.startsWith(PDF_URL_PREFIX) && !viewName.endsWith(".pdf")) {
            return getPdfView(viewName);
        }
        return null;
    }

    private View getPdfView(String viewName) {
        String pdfViewName = viewName.substring(PDF_URL_PREFIX.length());
        AppPdfView pdfView = BeanUtils.instantiateClass(AppPdfView.class);
        pdfView.setUrl(getPrefix() + pdfViewName);
        return applyLifecycleMethods(pdfViewName, pdfView);
    }

    private View getExcelView(String viewName) {
        String excelViewName = viewName.substring(EXCEL_URL_PREFIX.length());
        AppExcelView appExcelView = BeanUtils.instantiateClass(AppExcelView.class);
        appExcelView.setUrl(getPrefix() + excelViewName);
        return applyLifecycleMethods(excelViewName, appExcelView);
    }

    private View applyLifecycleMethods(String viewName, AbstractView view) {
        return (View) getApplicationContext().getAutowireCapableBeanFactory().initializeBean(view, viewName);
    }

    public String getPrefix() {
        return prefix;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    @Override
    public int getOrder() {
        return this.order;
    }

    public void setOrder(int order) {
        this.order = order;
    }
}
